﻿using System;
using System.Linq;

namespace BuzzX8.Xmpp.Server
{
    class Program
    {
        private static XmppServer server;
        private static CommandProcessor commandProcessor;

        static void Main(string[] args)
        {
            server = CreateServer(args);
            commandProcessor = CreateProcessor(server);
            ShowInitialMessage();
            server.Start();
            while (true)
            {
                Console.Write("> ");
                Command command = ParseCommand(Console.ReadLine());
                commandProcessor.Execute(command);
            }
        }

        private static void ShowInitialMessage()
        {
            Console.WriteLine("BuzzX8 Xmpp server console");
            Console.WriteLine();
        }

        private static XmppServer CreateServer(string[] args)
        {
            return new XmppServer();
        }

        private static CommandProcessor CreateProcessor(XmppServer server)
        {
            CommandProcessor processor = new CommandProcessor(server);
            processor.AddHandler("start-xmpp".GetHashCode(), (s, c) => s.Start());
            processor.AddHandler("exit".GetHashCode(), (s, c) => Environment.Exit(0));
            return processor;
        }

        private static Command ParseCommand(string commandLine)
        {
            string[] lexemas = commandLine.Trim().Split(' ').Select(s => s.Trim().ToLower()).ToArray();
            if (lexemas.Length == 0) return null;
            Command command = new Command(lexemas[0].GetHashCode());
            return command;
        }
    }
}
